package com.czq.mall.product.exception;

import com.czq.common.exception.ErrorEnum;
import com.czq.common.utils.R;
import lombok.extern.slf4j.Slf4j;
import org.springframework.validation.BindingResult;
import org.springframework.validation.FieldError;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @author Administrator
 * @date 2022/2/27 0027 20:51
 */
@Slf4j
@RestControllerAdvice
public class ExceptionAdvice {

    @ExceptionHandler(MethodArgumentNotValidException.class)
    public R handleValidException(MethodArgumentNotValidException e){
        log.error("数据校验异常",e);

        Map<String,String> messages = new HashMap<>();
        BindingResult bindingResult = e.getBindingResult();
        List<FieldError> fieldErrors = bindingResult.getFieldErrors();
        for (FieldError fieldError : fieldErrors){
            messages.put(fieldError.getField(),fieldError.getDefaultMessage());
        }
        return R.error(ErrorEnum.VOLID_EXCEPTION).put("data", messages);
    }

    @ExceptionHandler(Exception.class)
    public R handleException(Exception e){
        log.error("异常",e);
        return R.error(ErrorEnum.UNKNOW_EXCEPTION).put("data", "");
    }
}
